﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathematicallySafe.HeadCounter.Data.Common;
using StructureMap;

namespace MathematicallySafe.HeadCounter.Data.Models
{
    [Serializable]
    public class RaidHistory
    {
        private static Options Options;
        public SerializableSortedList<DateTime, Raid> RaidsDictionary;

        public DateTime WeekOneDate { get; set; }

        public RaidHistory()
        {
            Options = ObjectFactory.GetInstance<IHeadCounterService>().Options;
            RaidsDictionary = new SerializableSortedList<DateTime, Raid>();
        }

        public IEnumerable<Raid> Raids
        {
            get { return RaidsDictionary.Values; }
        }

        public bool HasRaids
        {
            get { return RaidsDictionary.Count() > 0; }
        }

        public void AddRaid(Raid raid)
        {
            if (RaidsDictionary.Count == 0)
            {
                SetStartWeek(raid.Date);
            }

            if (!RaidsDictionary.ContainsKey(raid.Date))
            {
                RaidsDictionary.Add(raid.Date, raid);
                OnRaidAdded(new RaidsHistoryChangedEventArgs(raid));
            }
        }

        public void RemoveRaid(Raid raid)
        {
            if (RaidsDictionary.ContainsKey(raid.Date))
            {
                RaidsDictionary.Remove(raid.Date);
                OnRaidRemoved(new RaidsHistoryChangedEventArgs(raid));
            }
        }

        public event EventHandler<RaidsHistoryChangedEventArgs> RaidAdded;
        public event EventHandler<RaidsHistoryChangedEventArgs> RaidRemoved;

        protected virtual void OnRaidAdded(RaidsHistoryChangedEventArgs e)
        {
            if (RaidAdded != null)
            {
                RaidAdded(this, e);
            }
        }

        protected virtual void OnRaidRemoved(RaidsHistoryChangedEventArgs e)
        {
            if (RaidRemoved != null)
            {
                RaidRemoved(this, e);
            }
        }

        private void SetStartWeek(DateTime firstRaidDate)
        {
            WeekOneDate = firstRaidDate.GetWeekStart(Options.Region);
        }

        public int LatestRaidWeek
        {
            get
            {
                var lastRaid = RaidsDictionary.Last().Value;
                return lastRaid.Date.GetWeekNumber();
            }
        }
    }

    public class RaidsHistoryChangedEventArgs : EventArgs
    {
        public readonly Raid Raid;

        public RaidsHistoryChangedEventArgs(Raid raid)
        {
            Raid = raid;
        }
    }
}